package com.li.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.li.constant.BaseContext;
import com.li.exception.BaseException;
import com.li.mapper.DictDateMapper;
import com.li.pojo.dto.DictDateDto;
import com.li.pojo.dto.DictDatePageDto;
import com.li.pojo.po.DictDate;
import com.li.pojo.po.PageResult;
import com.li.service.DictDateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 字典数据表 服务实现类
 * </p>
 *
 * @author author
 * @since 2024-04-11
 */
@Service
public class DictDateServiceImpl extends ServiceImpl<DictDateMapper, DictDate> implements DictDateService {
    @Autowired
    private DictDateMapper dictDateMapper;

    @Override
    public List<DictDate> findByDictType(String dictType) {
        List<DictDate> list=dictDateMapper.selectByDictType(dictType);
        return list;
    }

    @Override
    public void add(DictDateDto dictDateDto) {
        verify(dictDateDto);
        DictDate dictDate = new DictDate();
        BeanUtils.copyProperties(dictDateDto,dictDate);
        dictDate.setCreateBy(BaseContext.getCurrentName());
        dictDate.setUpdateBy(BaseContext.getCurrentName());
        dictDate.setCreateTime(LocalDateTime.now().toString());
        dictDate.setUpdateTime(LocalDateTime.now().toString());
        dictDateMapper.insert(dictDate);
    }

    @Override
    public PageResult findPage(DictDatePageDto pageDto) {
        Page<DictDate> page = PageHelper.startPage(pageDto.getPageNum(), pageDto.getPageSize());
        List<DictDate> list=dictDateMapper.findByPage(pageDto);
        return new PageResult(200,"查询成功",null,page.getResult(),page.getTotal());
    }

    @Override
    public void deleteByIds(List<Integer> dictIds) {
        dictDateMapper.deleteBatchIds(dictIds);
    }

    @Override
    public DictDate findByDictCode(Integer dictCode) {
        DictDate dictDate=dictDateMapper.findByDictCode(dictCode);
        return dictDate;
    }

    @Override
    public void updateDictDate(DictDateDto dictDateDto) {
        verify(dictDateDto);
        DictDate dictDate = new DictDate();
        BeanUtils.copyProperties(dictDateDto,dictDate);
        dictDate.setUpdateBy(BaseContext.getCurrentName());
        dictDate.setUpdateTime(LocalDateTime.now().toString());
        dictDateMapper.updateDictDate(dictDate);
    }

    //对字典在该类型里标签进行判断是否重复
    private void verify(DictDateDto dictDateDto) {
        List<DictDate> list = dictDateMapper.selectByDictLabel(dictDateDto.getDictLabel(), dictDateDto.getDictType());
        if (list.size()>0){
            throw new BaseException("字典标签重复");
        }
    }
}
